package com.xx566.blog.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
	HttpServletRequest orgRequest = null;

	public XssHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
		this.orgRequest = request;
	}

	public String getParameter(String name) {
		String value = super.getParameter(xssEncode(name));
		if (value != null) {
			value = xssEncode(value);
		}
		return value;
	}

	public String getHeader(String name) {
		String value = super.getHeader(xssEncode(name));
		if (value != null) {
			value = xssEncode(value);
		}
		return value;
	}

	private static String xssEncode(String s) {
		if ((s == null) || (s.isEmpty())) {
			return s;
		}
		StringBuilder sb = new StringBuilder(s.length() + 16);
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '>':
				sb.append(65310);
				break;
			case '<':
				sb.append(65308);
				break;
			case '\'':
				sb.append('‘');
				break;
			case '"':
				sb.append('“');
				break;
			case '&':
				sb.append(65286);
				break;
			case '\\':
				sb.append(65340);
				break;
			case '#':
				sb.append(65283);
				break;
			default:
				sb.append(c);
			}
		}

		return sb.toString();
	}

	public HttpServletRequest getOrgRequest() {
		return this.orgRequest;
	}

	public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
		if ((req instanceof XssHttpServletRequestWrapper)) {
			return ((XssHttpServletRequestWrapper) req).getOrgRequest();
		}

		return req;
	}
}